package cn.isgrow.gateway.filter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;


/**
 * 自定义局部过滤器
 * @author 朱开元
 * @Date 2020-05-23 15:26
 */

@Slf4j
@Component
public class AccessGatewayFilterFactory extends AbstractGatewayFilterFactory<AccessGatewayFilterFactory.Config> {
    public AccessGatewayFilterFactory() {
        super(AccessGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String token = exchange.getRequest().getQueryParams().getFirst(config.getTokenKey());
            if (null == token){
                ServerHttpResponse response = exchange.getResponse();
                // 设置响应类型
                response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String message = "{\"message\": + \"" + HttpStatus.UNAUTHORIZED.getReasonPhrase() + "\"}";
                DataBuffer buffer = response.bufferFactory().wrap(message.getBytes());
                return response.writeWith(Mono.just(buffer));
            }
            log.info("token is ok ");
            Mono<Void> filter = chain.filter(exchange);
            log.info("Response处理");
            return filter;
        };
    }

    @Data
    public static class Config {
        private String tokenKey;

    }
}
